﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using spbtzb;
public partial class Back_BgArticleList : System.Web.UI.Page
{
    private Boolean session_Logined
    {
        set
        {
            Session["Logined"] = value;
        }
        get
        {
            return Session["Logined"] == null ? false : Convert.ToBoolean(Session["Logined"]);
        }
    }

    private DataTable viewState_DtSrc
    {
        get
        {
            return ViewState["DtSrc"] == null ? null : (DataTable)ViewState["DtSrc"];
        }
        set
        {
            ViewState["DtSrc"] = value;
        }
    }

    string strSingle = "0";

    //private static String StrConn;
    protected String StrConn = ConString.ConnString;
    protected void Page_Load(object sender, EventArgs e)
    { 
        this.Page.Title = "文章管理页面";
        if (!this.Page.IsPostBack)
        {
            if (session_Logined == false)
            {
                Response.Redirect("Login.aspx?ErrorMessage=" + "您未登录，请在此登录");
            }
           
            //StrConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='E:\\spbtzbDB\\spbtzb.mdb';";
            
            Ddl_Types_BindData();
            ddl_Types_SelectedIndexChanged(new Object(), new EventArgs());
            
            
        }
    }

    private void Ddl_Types_BindData()
    {
        // generate datatable                       
        string sqlCmd = "SELECT * FROM ContentType WHERE ParentType = 'NO' OR ParentType = 'NOBB' OR ParentType = 'STBB' ORDER BY ID";
        System.Data.DataTable dtTypes = AccessHelper.ExecuteDataTable(StrConn, System.Data.CommandType.Text, sqlCmd);
        if (dtTypes.Rows.Count == 0)
        {
            // 没有相应类型的信息
            ScriptManager.RegisterStartupScript(UpdatePanel1, Page.GetType(), "deletesuccess", "alert('没有相应的类型数据！');", true);
            return;
        }
        this.ddl_Types.DataSource = dtTypes;
        this.ddl_Types.DataBind();
        
        
    }
    private void ddl_ChildTypes_BindData() 
    {
        string sqlCmd = String.Format("SELECT * FROM ContentType WHERE ParentType = '{0}' ORDER BY ID", this.ddl_Types.SelectedValue);
        System.Data.DataTable dtChildTypes = AccessHelper.ExecuteDataTable(StrConn, System.Data.CommandType.Text, sqlCmd);
        if (dtChildTypes == null || dtChildTypes.Rows.Count == 0) 
        {
            ddl_ChildTypes.Visible = true;
        }
        this.ddl_ChildTypes.DataSource = dtChildTypes;
        this.ddl_ChildTypes.DataBind();
        this.ddl_ChildTypes.SelectedIndex = 0;
        return;
    }

    protected void ddl_Types_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindData();
    }

    protected void BindData()
    {
        //if (this.ddl_Types.SelectedValue == "all")
        //{
        //    string sqlCmd = "SELECT Contents.*, ContentType.TypeName FROM Contents INNER JOIN ContentType "
        //                    + "On ContentType.TypeCode = Contents.TypeCode Order by Contents.CreateTime DESC,Contents.ID DESC  ";
        //    System.Data.DataTable dtContents = AccessHelper.ExecuteDataTable(StrConn, System.Data.CommandType.Text, sqlCmd);

        //    //if (dtContents.Rows.Count == 0)
        //    //{
        //    //    // 没有相应类型的信息
        //    //    RegisterClientScriptBlock("tip", "<script>alert('没有相应的类型数据！');</script>");
        //    //    return;
        //    //}
        //    this.gv_ArticalList.DataSource = dtContents;
        //    this.gv_ArticalList.DataBind();
        //    this.ddl_ChildTypes.Visible = false;
        //    viewState_DtSrc = dtContents;
        //}
        //else
        //{
        //不存在全选的问题了

            this.ddl_ChildTypes.Visible = true;
            
            // generate datatable                       
            string sqlCmd = String.Format("SELECT * FROM ContentType WHERE ParentType = '{0}' ORDER BY ID", this.ddl_Types.SelectedValue);
            System.Data.DataTable dtChildTypes = AccessHelper.ExecuteDataTable(StrConn, System.Data.CommandType.Text, sqlCmd);
            //如果是0 那么是公告 不是那么
            if (dtChildTypes == null || dtChildTypes.Rows.Count == 0)
            {
                this.ddl_ChildTypes.Visible = false;
                
                // 比如，如果是网站公告的话，那就得绑定相应数据                //
                string sqlNobbCmd = String.Format("SELECT Contents.*, ContentType.TypeName FROM Contents INNER JOIN ContentType "
                           + "On ContentType.TypeCode = Contents.TypeCode WHERE Contents.TypeCode = '{0}' "
                           + "Order by Contents.CreateTime DESC, Contents.ID DESC", this.ddl_Types.SelectedValue);
                System.Data.DataTable dtContents = AccessHelper.ExecuteDataTable(StrConn, System.Data.CommandType.Text, sqlNobbCmd);
            
                this.gv_ArticalList.DataSource = dtContents;
                this.gv_ArticalList.DataBind();
                viewState_DtSrc = dtContents;
                return;
            }
            this.ddl_ChildTypes.DataSource = dtChildTypes;

            this.ddl_ChildTypes.DataBind();
            ddl_ChildTypes_SelectedIndexChanged(new Object(), new EventArgs());
        
    }


    protected void btn_Eidt_Click(object sender, EventArgs e)
    {
        // 获取当前选择的index
        Button bt = (Button)sender;
        DataControlFieldCell dv = (DataControlFieldCell)bt.Parent;
        GridViewRow gvr = (GridViewRow)dv.Parent;
        int index = gvr.RowIndex;

        GridView gv = (GridView)gvr.Parent.Parent; // GridViewRow的Parent是GridView.ChildTable

        DataKeyArray dkCol = gv.DataKeys;
        long lID = Convert.ToInt64(dkCol[index].Value);
        Response.Redirect("BgArticleEdit.aspx?ID=" + lID);// 把该记录的id到编辑页面

        /*
               String add = "<script>window.open('PostInfo.aspx?ListNbr=" + strListNbr + "&QdType=" + strQdType + "', 'Add','width=500,height=550,resizable=yes,location=no,menubar=no,scrollbars=yes, status=no,toolbar=no,left=287,top=184').focus();</script>";

               RegisterClientScriptBlock("add", add); */

    }

    protected void btn_Del_Click(object sender, EventArgs e)
    {        
        // 获取当前选择的index
        Button btn = (Button)sender;
        DataControlFieldCell dv = (DataControlFieldCell)btn.Parent;
        GridViewRow gvr = (GridViewRow)dv.Parent;
        int index = gvr.RowIndex;

        GridView gv = (GridView)gvr.Parent.Parent; // GridViewRow的Parent是GridView.ChildTable

        DataKeyArray dkCol = gv.DataKeys;
        //The ArticleID
        long lID = Convert.ToInt64(dkCol[index].Value);
        if (lID < 0)
        {
            ScriptManager.RegisterStartupScript(UpdatePanel1, Page.GetType(), "deletesuccess", "alert('删除操作失败,请联系管理员！');", true);
            return;
        }

        string sqlCmd = String.Format("DELETE * FROM Contents WHERE ID = {0} ", lID);
        int iRet = AccessHelper.ExecuteNonQuery(StrConn, System.Data.CommandType.Text, sqlCmd);

        string sqlCmdDele = "Delete * from ContentAndType Where ContentID=" + lID.ToString();
        int delRes = AccessHelper.ExecuteNonQuery(StrConn, CommandType.Text, sqlCmdDele);

     
        if (iRet < 0|| delRes < 0)
        {
            ScriptManager.RegisterStartupScript(UpdatePanel1, Page.GetType(), "deletesuccess", "alert('删除操作失败,请联系管理员！');", true);
            return;
        }
        // RegisterClientScriptBlock("remind", "<script>alert('haha操作成功了！')</script>");
        ScriptManager.RegisterStartupScript(UpdatePanel1, Page.GetType(), "deletesuccess", "alert('删除操作成功！');", true);
        BindData();

    }

    protected void gv_ArticalList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        this.gv_ArticalList.PageIndex = e.NewPageIndex;    
        this.gv_ArticalList.DataSource = viewState_DtSrc;
        this.gv_ArticalList.DataBind();
    }

    protected void ddl_ChildTypes_SelectedIndexChanged(object sender, EventArgs e)
    {
        //if (this.ddl_ChildTypes.SelectedValue == "all")
        //{
        //    string sqlCmd = String.Format("select C.* ,CT.*,T.*  from Contents C, ContentAndType CT,ContentType T where C.ID=CT.ContentID And CT.TypeID=T.ID"+
        //        "And T.ParentType='{0}' And T.TypeCode='{0}'", this.ddl_Types.SelectedValue,this.ddl_ChildTypes.SelectedValue);
        //    System.Data.DataTable dtContents = AccessHelper.ExecuteDataTable(StrConn, System.Data.CommandType.Text, sqlCmd);
        //    //if (dtContents.Rows.Count == 0)
        //    //{
        //    //    // 没有相应类型的信息
        //    //    RegisterClientScriptBlock("tip", "<script>alert('没有相应的类型数据！');</script>");
        //    //    return;
        //    //}
        //    this.gv_ArticalList.DataSource = dtContents;
        //    this.gv_ArticalList.DataBind();
        //    viewState_DtSrc = dtContents;
        //}
        //else
        //{
            string sqlCmd = String.Format("select C.* ,T.TypeName  from Contents C, ContentAndType CT,ContentType T where C.ID=CT.ContentID And CT.TypeID=T.ID "+
                "And T.ParentType='{0}' And T.TypeCode='{1}'", this.ddl_Types.SelectedValue,this.ddl_ChildTypes.SelectedValue);
            System.Data.DataTable dtContents = AccessHelper.ExecuteDataTable(StrConn, System.Data.CommandType.Text, sqlCmd);

            string sqlCmdType = "select * from ContentType Where TypeCode='" + this.ddl_ChildTypes.SelectedValue + "'";
            System.Data.DataTable dtType = AccessHelper.ExecuteDataTable(StrConn, System.Data.CommandType.Text, sqlCmdType);
            strSingle = dtType.Rows[0]["IsSingle"].ToString();
            if (strSingle == "1")
            {

                btn_AddArticle.Visible = false;

            }

            this.gv_ArticalList.DataSource = dtContents;
            this.gv_ArticalList.DataBind();
            viewState_DtSrc = dtContents;
        //}

    }
    protected void btn_AddArticle_Click(object sender, EventArgs e)
    {
        // 不用管all选项
        if (!this.ddl_ChildTypes.Visible)
        {
            Response.Redirect("BgArticleAdd.aspx?fathertype=" + ddl_Types.SelectedValue);
        }
        else
        {
            Response.Redirect("BgArticleAdd.aspx?fathertype=" + 
                ddl_Types.SelectedValue + "&childtype=" + ddl_ChildTypes.SelectedValue);
        }      
    }

    protected string CutString(string title)
    {
        return Common.CutString(title);
    }

    protected void gv_ArticalList_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (strSingle == "1")
        {
            if (e.Row.RowType != DataControlRowType.EmptyDataRow && e.Row.RowType != DataControlRowType.Pager)
            {
                e.Row.Cells[6].Visible = false;
            }

        }
    }
}
